package CtrlLayer;
import java.util.ArrayList;
import ModelLayer.*;

public class LeaseController
{
    private LeaseContainer leaseContainer;
    private ProductController productController;
    public LeaseController(){
        leaseContainer = LeaseContainer.getInstance();
        productController = new ProductController();
    }

    public void createLeaseObjects(){  
        leaseContainer.addLease(new Lease(1221, "03-12-2014", "400004", 1, "30", 1, 1000));
    }

    public int createLease(String currentDate, String productBarcode, int amount, String period, int customerID, int sessionId){
        Lease lObject = null;
        int index = 0;
        int id = 0;
        while(index < leaseContainer.getLeaseList().size())
        {

            lObject = leaseContainer.getLeaseList().get(index); 
            if(lObject !=null){
                if(lObject.getId()>id)   
                    id = lObject.getId();
            }else{
                id = 1;
            }
            index++;
        }
        id++;
        int employeeID = SessionContainer.getInstance().findSessionById(sessionId).getPersonId();

        if(CustomerContainer.getInstance().checkCustomer(customerID)){
            leaseContainer.addLease(new Lease(id, currentDate, productBarcode, amount, period, employeeID, customerID));
            return id;
        }else{
            return 0;
        }
    }

    public boolean addProductInLease(int id, int productBarcode, int amount){
        if(!leaseContainer.findLeaseById(id).isReturned() &&  productController.findProduct(productBarcode) != null){
            leaseContainer.findLeaseById(id).addProduct(productBarcode,amount);   
            ProductContainer.getInstance().findProductByBarcode(productBarcode);//.recalculateAmount(amount);
            return true;
        }else{
            return false;
        }
    }

    public boolean removeProductFromLease(int id, int productBarcode, int amount){
        if(! leaseContainer.findLeaseById(id).isReturned() &&  productController.findProduct(productBarcode) != null){
            leaseContainer.findLeaseById(id).removeProduct(productBarcode, amount);
            ProductContainer.getInstance().findProductByBarcode(productBarcode).recalculateAmount(-amount);
            return true;
        }else{
            return false;
        }
    }

    public void endLease(int id){
        leaseContainer.findLeaseById(id).setReturned(true);
    }

    public Lease findLease(int id){    
        return  leaseContainer.findLeaseById(id);
    }

    public void deleteLease(int id){
        leaseContainer.deleteLease(leaseContainer.findLeaseById(id));
    }

}
